﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pifagor.IG;
using Pifagor.Exceptions;

namespace Pifagor.Runtime
{
	class Interpretation : IComputableValue
	{
		ExecutionContext _context;
		IComputableValue _argument;
		IComputableValue _function;
		Value _computedValue;

		internal Interpretation(ExecutionContext context, IComputableValue argument, IComputableValue function)
		{
			_context = context;
			_argument = argument;
			_function = function;
		}

		public Value Compute()
		{
			var argumentValue = _argument.Compute();
			var functionValue = _function.Compute();

			IFunction functionToRun = null;
			if (functionValue.Type == ValueType.ExternalFunction)
				functionToRun = functionValue.ExternalFunctionValue;
			else if (functionValue.Type == ValueType.InternalFunction)
				functionToRun = functionValue.InternalFunctionValue;

			if (functionToRun != null)
			{
				_computedValue = functionToRun.Run(argumentValue);
				return _computedValue;
			}

			throw new RuntimeException("Interpretation does not have a valid function");
		}

		public override string ToString()
		{
			return _computedValue == null ? base.ToString() : _computedValue.ToString();
		}
	}
}
